package com.tianpengtech.admin;

import java.util.Map;

import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.tianpengtech.common.exception.ServiceException;
import com.tianpengtech.common.exception.ValidateException;
import com.tianpengtech.common.search.QueryConstructor;

public abstract class AbstractAdmin {

    private String querySQLCommand="";

    public String getOrderClause() {
        return orderClause;
    }

    public void setOrderClause(String orderClause) {
        this.orderClause = orderClause;
    }

    private String orderClause="";


    public void setQuerySQLCommand(String querySQLCommand) {
        this.querySQLCommand = querySQLCommand;
    }


    public abstract void beforeAdd(Model<?> model) throws ValidateException;

    public abstract void beforeQueryById(Model<?>model,int id);

    public abstract void beforeUpdate(Model<?> model) throws ValidateException;

    public abstract void beforeDelete(Model<?> model);
   
    
    public Page<?> pageAllRecord(Model<?> model,int pageNum,int pageSize,Map<String,Object> params){


        QueryConstructor queryConstruct = new QueryConstructor();
        setQuerySQLCommand("select * ");
        setOrderClause(" order by id desc ");
		queryConstruct.setCommand("from "+tableName());
        queryConstruct.setOrderSql(orderClause);
        builderSQLExpected(model,queryConstruct,params);
        String sql = queryConstruct.buildSQL();
        return model.paginate(pageNum, pageSize,querySQLCommand, sql,queryConstruct.getParams().toArray());
    }
    
    /*
	 * 添加接口
	 */
	public boolean add(Model<?> model) throws ValidateException,ServiceException{
        beforeAdd(model);
		return model.save();
	}
	
	/*
	 * 更新指定记录接口
	 */
	public boolean updateById(Model<?> model)throws ValidateException,ServiceException{
        beforeUpdate(model);
		return model.update();
	}
	
	/*
	 * 删除指定记录接口
	 */
	public boolean deleteById(Model<?>model,int id)throws ValidateException,ServiceException{
		beforeDelete(model);
        return model.deleteById(id);
	}
    
	/*
	 * 查询指定记录接口
	 */
    public Model<?> queryById(Model<?>model,int id){
        beforeQueryById(model,id);
    	return model.findById(id);
    }
    
    /*
        根据查询条件创建对应的SQL语句
     */
    public abstract void builderSQLExpected(Model<?> model,QueryConstructor queryConstruct,Map<String,Object> params);
    
    public abstract String tableName();
}
